package fr.uparis10.miage.m1p1.menu;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.logging.Level;
import java.util.logging.Logger;

import fr.uparis10.miage.m1p1.global.LogFactory;

public class GenericMenu {
	private Logger log = LogFactory.getInstance().getLogger(
			GenericMenu.class.getName());

	// protected, in case somebody will want to modify the functionality
	protected ArrayList<MenuItemStruct> menuItems = new ArrayList<MenuItemStruct>();

	public void addMenuItem(MenuItemStruct menuItem) {
		menuItems.add(menuItem);
	}

	public void addMenuItems(MenuItemStruct[] menuItems) {
		for (MenuItemStruct menuItem : menuItems) {
			this.menuItems.add(menuItem);
		}
	}

	public void addMenuItems(Collection<MenuItemStruct> menuItems) {
		this.menuItems.addAll(menuItems);
	}

	public void show() {
		while (true) {
			System.out.println();
			for (int i = 0; i < menuItems.size(); i++) {
				System.out.println("\t\t(" + i + ")\t" + menuItems.get(i).text);
			}
			System.out.println("\t\t(x)\tExit");
			System.out.print("\tAction?: ");
			byte[] buf = new byte[100];
			try {
				System.in.read(buf);
			} catch (IOException exc) {
				log.log(Level.SEVERE, "Exception occured: ", exc);
			}
			String action = (new String(buf)).trim().toLowerCase();
			if (action.equals("x")) {
				// Exit
				return;
			}
			int itemId;
			try {
				itemId = Integer.parseInt(action);
				menuItems.get(itemId).executor.execute();
			} catch (NumberFormatException exc) {
				log.log(Level.WARNING, "Invalid action", exc);
				// print everything again
				continue;
			} catch (IndexOutOfBoundsException exc) {
				log.log(Level.WARNING, "No such action defined", exc);
				// print everything again
				continue;
			} catch (NullPointerException exc) {
				log.log(Level.WARNING, "Undefined executor", exc);
				// print everything again
				continue;
			}
		}
	}
}
